package com.baidu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.baidu.constant.MessageConstant;
import com.baidu.constant.RedisMessageConstant;
import com.baidu.entity.Result;
import com.baidu.pojo.Order;
import com.baidu.service.OrderService;
import com.baidu.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
	@Autowired
	private JedisPool jedisPool;

	@Reference
	private OrderService orderService;


	@RequestMapping("/submit")
	public Result submit(@RequestBody Map map) {
//从redis中获取缓存的验证码，所以要获的参数传递过来的电话号码

		String telephone = (String) map.get("telephone");

		String redisCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
		System.out.println("redisCode=" + redisCode);
		String validateCode = (String) map.get("validateCode");
		System.out.println("validateCode=" + validateCode);
//		将用户输入的验证码和Redis中保存的验证满进行比较，比较成功，则调用服务，比较不成功 则返回结果给页面


		if (redisCode != null && validateCode != null && redisCode.equals(validateCode)) {
			Result result = new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
//验证码比对成功，调用服务层处理业务
			map.put("orderType", Order.ORDERTYPE_WEIXIN);

			try {//属于网络远程调用，有可能会出现异常
				result = orderService.order(map);
			} catch (Exception e) {
				e.printStackTrace();
				return result;
			}
			if (result.isFlag()) {
				//预约成功，发短信
				try {
					SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
				} catch (ClientException e) {
					return new Result(false, "网络不稳定，请稍后再试");
				}

				return result;

			}

			return result;
		} else {

			return new Result(false, MessageConstant.VALIDATECODE_ERROR);

		}


	}

@RequestMapping("/findById")
	public Result findById(Integer id){

	try {
		Map order=orderService.findById(id);

		return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,order);
	} catch (Exception e) {
		return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
	}
}


}
